<template>
  <div class="code-highlight">
    <div class="code-header" v-if="showHeader">
      <span class="language">{{ language }}</span>
      <el-button 
        type="primary" 
        link 
        size="small" 
        @click="copyCode"
        :icon="DocumentCopy"
      >
        复制代码
      </el-button>
    </div>
    <pre v-if="code"><code :class="codeClass" ref="codeRef">{{ code }}</code></pre>
    <slot v-else></slot>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import hljs from 'highlight.js'
import { DocumentCopy } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 导入常用的语言
import 'highlight.js/lib/languages/javascript'
import 'highlight.js/lib/languages/typescript'
import 'highlight.js/lib/languages/xml'
import 'highlight.js/lib/languages/css'
import 'highlight.js/lib/languages/scss'
import 'highlight.js/lib/languages/sql'
import 'highlight.js/lib/languages/json'
import 'highlight.js/lib/languages/bash'
import 'highlight.js/lib/languages/markdown'

// 导入主题样式 (这里使用 github 主题)
import 'highlight.js/styles/github.css'

const props = defineProps({
  code: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'typescript'
  },
  showHeader: {
    type: Boolean,
    default: true
  },
  theme: {
    type: String,
    default: 'vscode'
  }
})

const codeRef = ref<HTMLElement | null>(null)
const codeClass = computed(() => `language-${props.language}`)

// 高亮代码
const highlightCode = () => {
  if (codeRef.value) {
    hljs.highlightElement(codeRef.value)
  }
}

// 复制代码
const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code || codeRef.value?.textContent || '')
    ElMessage.success('复制成功')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 监听代码变化
watch(() => props.code, () => {
  nextTick(() => {
    highlightCode()
  })
})

onMounted(() => {
  highlightCode()
})
</script>

<style scoped lang="scss">
.code-highlight {
  margin: 16px 0;
  border-radius: 6px;
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: var(--el-box-shadow-light);
  }

  .code-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    background: var(--el-bg-color-page);
    border-bottom: 1px solid var(--el-border-color-light);

    .language {
      color: var(--el-text-color-secondary);
      font-size: 12px;
      text-transform: uppercase;
    }
  }

  pre {
    margin: 0;
    padding: 16px;
    overflow-x: auto;

    code {
      font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
      padding: 0;
      background: transparent;
    }
  }
}

:deep(.hljs) {
  background: transparent;
}
</style> 